from django.http import HttpResponse, JsonResponse
from django.shortcuts import render
from django.views import View
from django_redis import get_redis_connection

# Create your views here.
from users.models import Users
from verifications import constants
from verifications.imgCodes import ValidImgCode

def register(request):
    # return HttpResponse('你好')
    return render(request, 'verifications/register.html')

class CkeckUsernameView(View):

    def get(self, request, username):
        count = Users.objects.filter(username=username).count()
        data = {
            'username': username,
            'count': count
        }

        return JsonResponse(data=data)

class ImageCode(View):
    """create image code
        #1 创建类试图
    """
    def get(self, request, image_code_id):
        # 生成图片验证码及图片验证码文本
        # image.write('1234', 'out.png')
        img = ValidImgCode()
        # valid_str, image = ValidImgCode.generate_captcha()
        valid_str, image = img.imgcode_captcha()
        # 保存图片验证码文本到redis
        con_redis = get_redis_connection(alias="verify_codes")
        img_key = 'img{}'.format(image_code_id).encode('utf-8')
        con_redis.setex(img_key, constants.IMAGE_CODE_REDIS_EXPIRES, valid_str)

        # 固定返回验证码图片数据，不需要REST framework框架的Response帮助我们决定返回响应数据的格式
        # 所以此处直接使用Django原生的HttpResponse即可
        return HttpResponse(image, content_type="image/jpg")
